package com.alphas.user_centbackendalphas.service.impl;

import com.alphas.user_centbackendalphas.common.BaseResponse;
import com.alphas.user_centbackendalphas.common.StatusCode;
import com.alphas.user_centbackendalphas.exception.BusinessException;
import com.alphas.user_centbackendalphas.mapper.UserMapper;
import com.alphas.user_centbackendalphas.model.domain.User;
import com.alphas.user_centbackendalphas.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.alphas.user_centbackendalphas.constant.Constant.ADMIN_ROLE;
import static com.alphas.user_centbackendalphas.constant.Constant.USER_LOGIN_STATE;

/**
* @author Alphas
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-06-12 15:11:19
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Resource
    private UserMapper userMapper;
    //加密用的盐值
    private static final String SALT = "alphas";

    @Override
    public BaseResponse<Long> userRegister(String userAccount, String userPassword, String checkPassword) {
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(StatusCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }

        // 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(StatusCode.UNKNOWN_ERROR);
        }
        return BaseResponse.success(user.getId());
    }

    @Override
    public BaseResponse<User> userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(StatusCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(StatusCode.PARAM_ERROR);
        }

        //校验密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(StatusCode.NOT_FOUND);
        }
        //用户存在，返回用户信息(脱敏)
        User safetyUser = getSafetyUser(user);
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return BaseResponse.success(safetyUser);
    }

    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUserName(originUser.getUserName());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        return safetyUser;
    }

    @Override
    public BaseResponse<List<User>> userSearch(HttpServletRequest request, String username) {
        if (isAdmin(request)){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like("user_name",username);
            List<User> list = this.list(userQueryWrapper);
            List<User> collect = list.stream().map(this::getSafetyUser).collect(Collectors.toList());
            return BaseResponse.success(collect);
        }
        throw new BusinessException(StatusCode.UNAUTHORIZED);
    }

    @Override
    public BaseResponse<Boolean> deleteUser(HttpServletRequest request, long userId) {
        if (isAdmin(request)){
            boolean b = this.removeById(userId);
            return BaseResponse.success(b);
        }
        throw new BusinessException(StatusCode.UNAUTHORIZED);
    }

    @Override
    public BaseResponse<User> getCurrentUserInfo(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) attribute;
        Long id = user.getId();
        User byId = userMapper.selectById(id);
        User safetyUser = this.getSafetyUser(byId);
        return BaseResponse.success(safetyUser);
    }

    @Override
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return BaseResponse.success(0);
    }

    public boolean isAdmin(HttpServletRequest request){
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) attribute;
        Integer userRole = user.getUserRole();
        return userRole == ADMIN_ROLE;
    }

}




